package com.mvvmhabit.org.binding.viewadapter.view

import android.annotation.SuppressLint
import android.view.View
import androidx.databinding.BindingAdapter
import com.jakewharton.rxbinding2.view.RxView
import com.mvvmhabit.org.binding.command.BindingCommand
import java.util.concurrent.TimeUnit

private const val CLICK_INTERVAL = 1L

@SuppressLint("CheckResult")
@BindingAdapter(value = ["onClickCommand", "isThrottleFirst"], requireAll = false)
fun onClickCommand(view: View, clickCommand: BindingCommand<Any>, isThrottleFirst: Boolean) {
    if (isThrottleFirst) {
        RxView.clicks(view)
            .subscribe {
                clickCommand.execute()
            }
    } else {
        RxView.clicks(view)
            .throttleFirst(CLICK_INTERVAL, TimeUnit.SECONDS)
            .subscribe {
                clickCommand.execute()
            }
    }
}

/**
 * view的焦点发生变化的事件绑定
 */
@BindingAdapter(value = ["onFocusChangeCommand"])
fun onFocusChangeCommand(view: View, onFocusChangeCommand: BindingCommand<Boolean>) {
    view.setOnFocusChangeListener { _, b ->
        onFocusChangeCommand.execute(b)
    }
}

/**
 * view的显示隐藏
 */
@BindingAdapter(value = ["isVisible"], requireAll = false)
fun isVisible(view: View, visibility: Boolean) {
    if (visibility) {
        view.visibility = View.VISIBLE
    } else {
        view.visibility = View.GONE
    }
}